package com.apache.client;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.collections.map.CaseInsensitiveMap;
public class StringUtil {

	/** 
	* 将一个 JavaBean 对象转化为一个  Map 
	* @param bean 要转化的JavaBean 对象 
	* @return 转化出来的  Map 对象 
	* @throws IntrospectionException 如果分析类属性失败 
	*/
	public static Map convertBean(Object bean) throws IntrospectionException {
		Class type = bean.getClass();
		Map returnMap = new CaseInsensitiveMap();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);
		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				try {
					Method readMethod = descriptor.getReadMethod();
					Object result = readMethod.invoke(bean, new Object[0]);
					if (!isEmpty(result)) {
						returnMap.put(propertyName.toLowerCase(), result);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return returnMap;
	}

	/**
	 *判断对象是否为空
	 * 
	 * @param  obj 传入的对象
	 * @return     如果obj为空返回true，不为空返回false  
	 */
	private static boolean isEmpty(Object obj) {
		return obj == null;
	}

	/**
	 * 属性值生成,符合骆驼命名
	 */
	public static String toCamelNamed(String str) {
		String names[] = str.split("_");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < names.length; i++) {
			if (i == 0) {
				sb.append(names[i].toLowerCase());
			} else {
				sb.append(names[i].substring(0, 1).toUpperCase() + names[i].substring(1).toLowerCase());
			}
		}
		return sb.toString();
	}

	/**
	 * description:  将类属性改成数据字段名
	 */
	public static String upperCharToUnderLine(String param) {
		Pattern p = Pattern.compile("[A-Z]");
		if (param == null || param.equals("")) {
			return "";
		}
		StringBuilder builder = new StringBuilder(param);
		Matcher mc = p.matcher(param);
		int i = 0;
		while (mc.find()) {
			builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
			i++;
		}
		if ('_' == builder.charAt(0)) {
			builder.deleteCharAt(0);
		}
		return builder.toString();
	}
}
